import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
  showSpinner: false
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  console.log(to, from)
  if (to.name === 'login') {
    next()
    return
  }

  if (!store.state.user.token) {
    next({ name: 'login', replace: true })
    return
  }

  if (['loading', 'err403', 'err404', 'err500'].includes(to.name)) {
    next()
    return
  }

  if (to.name !== 'home' && from.path === '/' && !from.name && !store.state.app.options.length && (to.meta && !to.meta._blank)) {
    next({ name: 'home' })
    return
  }

  if (to.name === from.name) {
    next({ name: 'empty', params: { to: to } })
    return
  }

  to.params && to.params.meta && to.params.meta.reload && store.commit('DEL_CACHE', to.path)
  next()
})

router.afterEach(() => {
  NProgress.done()
})
